import 'dart:convert';
import 'package:chewie/chewie.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:play_lab/core/helper/string_format_helper.dart';
import 'package:play_lab/data/model/authorization/authorization_response_model.dart';
import 'package:play_lab/data/model/global/response_model/response_model.dart';
import 'package:play_lab/data/model/live_tv/live_tv_comments_response_model.dart';
import 'package:play_lab/data/model/live_tv/live_tv_details_response_model.dart';
import 'package:play_lab/data/repo/live_tv_repo/live_tv_repo.dart';
import 'package:play_lab/view/components/show_custom_snackbar.dart';
import 'package:video_player/video_player.dart';
import '../../../constants/my_strings.dart';
import '../../../core/utils/my_color.dart';
import '../../../core/utils/styles.dart';

class LiveTvDetailsController extends GetxController {
  LiveTvRepo repo;
  LiveTvDetailsController({required this.repo});
  // WsSocketService wsService = WsSocketService();
  bool isLoading = true;
  bool isChewieInitialize = false;

  late VideoPlayerController videoPlayerController;
  late ChewieController chewieController;

  List<RelatedTv> relatedTvList = [];
  List<LiveChatCommentModel> liveTvCommentList = <LiveChatCommentModel>[];
  String imagePath = '';
  Tv tvObject = Tv();

  @override
  void onClose() {
    try {
      videoPlayerController.dispose();
      chewieController.dispose();
    } catch (e) {
      print(e.toString());
    }

    videoUrl = '';
    isLoading = true;
    super.onClose();
  }

  Future<dynamic> initializePlayer(String s) async {
    videoPlayerController = VideoPlayerController.networkUrl(Uri.parse(s));

    try {
      await videoPlayerController.initialize();
      chewieController = ChewieController(
        videoPlayerController: videoPlayerController,
        aspectRatio: 4 / 2,
        autoPlay: true,
        isLive: true,
        allowedScreenSleep: false,
        allowFullScreen: true,
        looping: true,
        autoInitialize: true,
        showControls: true,
        errorBuilder: (context, error) {
          String errorMessage = '';
          if (error.contains('VideoError')) {
            errorMessage = MyStrings.videoSourceError;
          } else if (error.contains('PlatformException')) {
            errorMessage = MyStrings.platformSpecificError;
          } else {
            errorMessage = MyStrings.unknownVideoError;
          }
          return Padding(
            padding: const EdgeInsets.symmetric(horizontal: 15.0),
            child: Center(
              child: Text(
                errorMessage.tr,
                style: boldDefault.copyWith(color: MyColor.colorWhite),
                overflow: TextOverflow.ellipsis,
                maxLines: 2,
                textAlign: TextAlign.center,
              ),
            ),
          );
        },
      );

      chewieController.addListener(() {
        if (videoPlayerController.value.position == videoPlayerController.value.duration) {}
      });

      videoUrl = s;
      isChewieInitialize = true;
    } catch (e) {
      isChewieInitialize = false;
      printX('error: ${e.toString()}');
    }

    isLoading = false;
    update();
  }

  String videoUrl = '';
  Future<void> getTvDetails(String liveTv) async {
    isLoading = true;
    ResponseModel model = await repo.getLiveTvDetails(liveTv);

    if (model.statusCode == 200) {
      LiveTvDetailsResponseModel responseModel = LiveTvDetailsResponseModel.fromJson(jsonDecode(model.responseJson));
      if (responseModel.status == 'success') {
        tvObject = responseModel.data!.tv!;
        imagePath = responseModel.data?.imagePath ?? '';
        if (responseModel.data?.relatedTv != null && responseModel.data!.relatedTv != []) {
          relatedTvList.clear();
          relatedTvList.addAll(responseModel.data!.relatedTv!);
        }
        printX("responseModel.data?.tv?.url -> ${responseModel.data?.tv?.url}");
        await initializePlayer(responseModel.data?.tv?.url ?? '').then((v) {
          getCommentList(liveTv);
          // wsService.connect(liveTv);
        });
      } else {
        Get.back();
        CustomSnackbar.showCustomSnackbar(errorList: responseModel.message?.error ?? [], msg: [], isError: true);
      }
    } else {
      CustomSnackbar.showCustomSnackbar(errorList: [model.message], msg: [], isError: true);
    }
    isLoading = false;
    update();
  }

  Future<void> getCommentList(String tvId) async {
    try {
      ResponseModel responseModel = await repo.getLiveTvCommentList(tvId);
      if (responseModel.statusCode == 200) {
        printX(responseModel.responseJson);

        LiveTvChatResponseModel model = liveTvChatResponseModelFromJson(responseModel.responseJson);
        if (model.status == "success") {
          liveTvCommentList = model.data?.comments ?? [];
        } else {
          CustomSnackbar.showCustomSnackbar(errorList: model.message?.error ?? [MyStrings.somethingWentWrong], msg: [], isError: true);
        }
      } else {
        CustomSnackbar.showCustomSnackbar(errorList: [responseModel.message], msg: [], isError: true);
      }
    } catch (e) {
      printX(e);
    } finally {}
    isLoading = false;
    update();
  }

  bool isSubmitLoading = false;
  Future<void> submitComment(String comment) async {
    isSubmitLoading = true;
    update();
    try {
      ResponseModel responseModel = await repo.submitComment(tvId: tvObject.id.toString(), comments: comment);
      if (responseModel.statusCode == 200) {
        AuthorizationResponseModel model = AuthorizationResponseModel.fromJson(jsonDecode(responseModel.responseJson));
        if (model.status == "success") {
          getCommentList(tvObject.id.toString());
        } else {
          CustomSnackbar.showCustomSnackbar(errorList: model.message?.error ?? [MyStrings.somethingWentWrong], msg: [], isError: true);
        }
      } else {
        CustomSnackbar.showCustomSnackbar(errorList: [responseModel.message], msg: [], isError: true);
      }
    } catch (e) {
      printX(e.toString());
    }
    isSubmitLoading = false;
    update();
  }

  void clearAllData() {
    try {
      isLoading = true;
      isChewieInitialize = true;
      videoUrl = '';
      relatedTvList.clear();
      videoPlayerController.dispose();
      chewieController.dispose();
      // wsService.disconnect();
    } catch (e) {
      e.printInfo();
    }
  }
}
